package gokyesil.game.aygitciklar.controller;


import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.World;

public class GroundContact implements ContactListener {

	private Vector2 normal;
	private Body aygitBody;
	private World world;
	private GroundNormal groundNormal;
	private int contactNumber;
	public Vector2 impulse;
	public GroundContact(Body _aygitBody, World _world, GroundNormal _groundNormal)
	{
		world = _world;
		groundNormal = _groundNormal;
		aygitBody = _aygitBody;
		normal = new Vector2(0,0);
		contactNumber = 0;
		impulse = new Vector2(0,0);
	}
	public void beginContact(Contact contact) {
		// TODO Auto-generated method stub
		if((contact.getFixtureA().getBody() == aygitBody) || (contact.getFixtureB().getBody() == aygitBody))
		{	
			Vector2 from = new Vector2(aygitBody.getPosition());
			Vector2 to = new Vector2(aygitBody.getPosition().x, aygitBody.getPosition().y-1.0f);
			world.rayCast(groundNormal, from, to);
			if(contactNumber == 0)
			{
				normal.set(groundNormal.normal);
				impulse.set(normal.mul(30.0f).add(0,16.0f));
			}
			else
			{
				System.out.println("angles "+groundNormal.normal.angle()*180/Math.PI+" "+normal.angle()*180/Math.PI);
				//System.out.println("angles "+Math.abs(groundNormal.normal.angle()-Math.PI/2.0)*180/Math.PI +" "+ Math.abs(normal.angle()-Math.PI/2.0)*180/Math.PI);
				if(Math.abs(groundNormal.normal.angle()-Math.PI/2.0)%Math.PI < Math.abs(normal.angle()-Math.PI/2.0)%Math.PI)
				{
					normal.set(groundNormal.normal);
					impulse.set(normal.mul(30.0f).add(0,16.0f));
				}
			}
			contactNumber++;
			System.out.println("the Contact has begun /t "+contactNumber+" "+normal);
		}
	}


	@Override
	public void endContact(Contact contact) {
		if(contact.getFixtureA().getBody() == aygitBody || contact.getFixtureB().getBody() == aygitBody)
		{
			contactNumber--;
			System.out.println("the Contact has finished /t "+contactNumber+" "+normal);
			if(contactNumber == 0)
			{
				impulse.set(0, 0);
			}
		}
	}

	@Override
	public void postSolve(Contact arg0, ContactImpulse arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void preSolve(Contact arg0, Manifold arg1) {
		// TODO Auto-generated method stub

	}

}
